package cn.jiedanba.itext5.gm.sign.test;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

import com.cwca.certServer.common.utils.UUIDUtils;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.bouncycastle.jcajce.provider.digest.SM3;
import org.ofdrw.gm.ses.v4.SESeal;
import org.ofdrw.sign.signContainer.MyV4Container;
import org.ofdrw.sign.signContainer.SESV4Container;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.security.TSAClient;

import cn.jiedanba.itext5.BCProvider;
import cn.jiedanba.itext5.gm.sign.ITextGM;
import cn.jiedanba.itext5.gm.sign.timestamp.GMTSAClient;
import cn.jiedanba.itext5.gm.sign.timestamp.GMTimeStampHook;
import cn.jiedanba.itext5.gm.sign.vo.GetPdfHash;
import cn.jiedanba.itext5.gm.sign.vo.GetPdfHashParamVo;
import cn.jiedanba.itext5.util.PkiUtil;

/**
 * 国密 pdf签名测试
 * 
 * @author dell
 *
 */
public class SignPdf extends BCProvider {

	//private static String cert = "MIID7DCCA5CgAwIBAgIIEAAAAAGR1mEwDAYIKoEcz1UBg3UFADBlMQswCQYDVQQGEwJDTjEQMA4GA1UECAwHR3Vhbmd4aTEQMA4GA1UEBwwHTmFuTmluZzEVMBMGA1UECgwMR3Vhbmd4aUNvdXJ0MRswGQYDVQQDDBJHdWFuZ3hpQ291cnRDQS1TTTIwHhcNMjIxMDEzMTAxNjA3WhcNMjMxMDEzMTAxNjA3WjCBszEbMBkGA1UEAwwS6K+J6K685pyN5Yqh6K+B5LmmMSEwHwYDVQQLDBjor4norrzmnI3liqHnm5bnq6Dns7vnu58xMDAuBgNVBAoMJ+W5v+ilv+WjruaXj+iHqu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EDAOBgNVBAcMB05hbk5pbmcxFTATBgNVBAoMDEd1YW5neGlDb3VydDEbMBkGA1UEAwwSR3Vhbmd4aUNvdXJ0Q0EtU00yMAwGA1UdEwQFMAMBAQAwDAYIKoEcz1UBg3UFAANIADBFAiEA+Onb7Cn41AFhJvrPq0rUDDjk8fS4u4diNpyodDlL774CIF+j1KSjppKAZ0Yb9MW1Zl0ZObqkVbm96eX9kIWiPiXZ";
	private static String privateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQg5PcUVT35q5vpffnZ7aUR8/7GQS2O5KbvRZl568OeoQ6gCgYIKoEcz1UBgi2hRANCAAR8vc0gHV7R+n4vWksUk7HLqT/qZcZXR48EIgpB0RktvBOUpJX/MwZYNc3YWDi0KJmqg68aJSEJQNG9XF3I1okm";

	public static void sign() throws IOException, GeneralSecurityException, DocumentException {
		GetPdfHashParamVo paramVo = new GetPdfHashParamVo();
		//Path pdf = Paths.get("src/main/resources", "sign.pdf");
		Path pdf = Paths.get("D:\\test1704.pdf");
		paramVo.setPdf(Files.readAllBytes(pdf));
		paramVo.setPageNo(1);
		paramVo.setLlx(250);
		paramVo.setLly(310);
		paramVo.setUrx(paramVo.getLlx() + 120);
		paramVo.setUry(paramVo.getLly() + 120);
		Path seal = Paths.get("D:/data/file/lawsuitSeal/seal/2768/fb0ecfd4caf1473d83af0bc8d4bd5f71.esl");
		paramVo.setSeal(SESeal.getInstance(Files.readAllBytes(seal)));
		paramVo.setLocation("广西高院");
		paramVo.setReason("国密电子签章测试");

		// 创建签名域，获取pdf文件摘要
		GetPdfHash getPdfHash = ITextGM.getPdfHash(paramVo);
//我们没有时间戳服务器
//		TSAClient tsaClient = new GMTSAClient(new URL("https://pki.jiedanba.cn/tsa/sign?type=SM2"), null, null,
//				new SM3.Digest());

		PrivateKey prvKey = PkiUtil.getPrivateKey(Base64.decodeBase64(privateKey));

		X509Certificate signCert = PkiUtil.readX509Certificate(java.util.Base64.getDecoder().decode(cert));

		// 签署摘要，以下为模拟外部签名测试，电子签章请使用符合国家规范具有国家型号证书的设备进行
		SESV4Container signature = new SESV4Container(paramVo.getSeal(), signCert);
		//GMTimeStampHook timeStampHook = new GMTimeStampHook(tsaClient);
		//signature.setTimeStampHook(null);
		String uuid = UUIDUtils.getUUID();
		byte[] p7 = signature.sign(getPdfHash.getDigesHash(), uuid);

		// 签署pdf
		byte[] signSuccess = ITextGM.signDeferred(getPdfHash.getEmptySignaturePdf(), p7, getPdfHash.getFieldName());

		//在这里加密试试
//		InputStream is = new ByteArrayInputStream(signSuccess);
//		OutputStream os  = new FileOutputStream("D:/test1706.pdf");
//		PdfReader reader = new PdfReader(is);
//		PdfStamper stamper = new PdfStamper(reader, os);
//		stamper.setEncryption(
//				null,
//				"123456".getBytes(),
//				PdfWriter.ALLOW_PRINTING,
//				PdfWriter.ENCRYPTION_AES_256);
//		stamper.close();


		FileUtils.writeByteArrayToFile(new File("D:\\test1706.pdf"), signSuccess);
	}

	public static void main(String[] args) throws IOException, GeneralSecurityException, DocumentException {
		sign();
		//entryPdf();
	}


	public static void entryPdf() throws IOException, DocumentException {

		InputStream is  = new FileInputStream("D:/test1705.pdf");
		OutputStream os  = new FileOutputStream("D:/test1706.pdf");
		// is为pdf文件输入流，os为要输出的文件流
		PdfReader reader = new PdfReader(is);
		PdfStamper stamper = new PdfStamper(reader, os);
		// 设密码，禁止编辑
		stamper.setEncryption(
				null,
				"123456".getBytes(),
				PdfWriter.ALLOW_PRINTING,
				PdfWriter.ENCRYPTION_AES_256);

		//reader.close();
		stamper.close();

	}
}
